package com.zondy.mapgis.android.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.zondy.mapgis.android.utils.DialogUtil;
import com.zondy.mapgis.android.view.CustomNestRadioGroup;
import com.zondy.mapgis.android.view.ExpandAnimation;
import com.zondy.mapgis.core.srs.ElpTransParam;
import com.zondy.mapgis.map.model.ConfigManager;
import com.zondy.mapgis.explorer.R;

/**
 * @content 定位数据转换工具
 * @author fjl 2016-12-6 上午11:33:20
 */

public class LocationTransActivity extends Activity implements OnClickListener
{
	public String TAG = this.getClass().getSimpleName();
	private ConfigManager mConfigManager;
	private ElpTransParam mElpTransParam;

	private SimpleAdapter mThreeParamadapter;
	private ListView mThreeParamHisListView = null;
	private String[] mThreeParamHisArrays = new String[] {};
	private String[] mSevenParamHisArrays = new String[] {};

	public RelativeLayout mLocationTwoLayout;
	public RelativeLayout mLocationThreeLayout;
	public View mLocationTwoView;
	public View mLocationThreeView;
	public CheckBox mThreeParamsCb;
	public CheckBox mSevenParamsCb;
	public RadioButton mGcjRd;
	public RadioButton mGpsRd;

	/** 三参数，七参数 **/
	public EditText mDxEt;
	public EditText mDyEt;
	public EditText mDzEt;
	public EditText mDxEt7;
	public EditText mDyEt7;
	public EditText mDzEt7;
	public EditText mWxEt;
	public EditText mWyEt;
	public EditText mWzEt;
	public EditText mDmEt;
	public TextView mThreeParamsHisTv;
	public TextView mSevenParamsHisTv;

	private TextView mTile = null;
	private ImageView mTileBack = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.location_trans_layout);
		//透明状态栏  
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);  
        //透明导航栏  
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

		initView();
	}

	/**
	 * 初始化窗体
	 */
	private void initView()
	{
		mTile = (TextView) findViewById(R.id.title_text);
		mTile.setText("定位数据转换");
		mTileBack = (ImageView) findViewById(R.id.title_back);
		mLocationTwoLayout = (RelativeLayout) findViewById(R.id.location_trans_titile2);
		mLocationThreeLayout = (RelativeLayout) findViewById(R.id.location_trans_titile3);
		mThreeParamsCb = (CheckBox) findViewById(R.id.three_params_cb);
		mSevenParamsCb = (CheckBox) findViewById(R.id.seven_params_cb);
		mGcjRd = (RadioButton) findViewById(R.id.gcj_coord_rb);
		mGpsRd = (RadioButton) findViewById(R.id.gps_coord_rb);
		mDxEt = (EditText) findViewById(R.id.dx);
		mDyEt = (EditText) findViewById(R.id.dy);
		mDzEt = (EditText) findViewById(R.id.dz);
		mDxEt7 = (EditText) findViewById(R.id.dx7);
		mDyEt7 = (EditText) findViewById(R.id.dy7);
		mDzEt7 = (EditText) findViewById(R.id.dz7);
		mWxEt = (EditText) findViewById(R.id.wx);
		mWyEt = (EditText) findViewById(R.id.wy);
		mWzEt = (EditText) findViewById(R.id.wz);
		mDmEt = (EditText) findViewById(R.id.dm);
		mThreeParamsHisTv = (TextView) findViewById(R.id.threeparams_history_tv);
		mSevenParamsHisTv = (TextView) findViewById(R.id.sevenparams_history_tv);

		mLocationTwoView = findViewById(R.id.locationtwo_view);
		mLocationThreeView = findViewById(R.id.locationthree_view);
		// mLocationTwoView.setVisibility(View.GONE);
		// mLocationThreeView.setVisibility(View.GONE);

		mLocationTwoLayout.setOnClickListener(this);
		mLocationThreeLayout.setOnClickListener(this);
		mSevenParamsCb.setOnClickListener(this);
		mThreeParamsCb.setOnClickListener(this);
		mThreeParamsHisTv.setOnClickListener(this);
		mSevenParamsHisTv.setOnClickListener(this);
		mTileBack.setOnClickListener(this);

		mConfigManager = ConfigManager.getInstance(getApplicationContext());
		mElpTransParam = new ElpTransParam();

		CustomNestRadioGroup coordRadioGroup = (CustomNestRadioGroup) findViewById(R.id.coord_type_rg);
		coordRadioGroup.setOnCheckedChangeListener(new RadioButtonListen());

		if (mConfigManager.getCoordType().equalsIgnoreCase("GPS"))
		{
			mGpsRd.setChecked(true);
		}
		if (mConfigManager.getCoordType().equalsIgnoreCase("GCJ02"))
		{
			mGcjRd.setChecked(true);
		}
		if (mConfigManager.getTransStr().equalsIgnoreCase("三参数"))
		{
			mThreeParamsCb.setChecked(true);
		}
		if (mConfigManager.getTransStr().equalsIgnoreCase("七参数"))
		{
			mSevenParamsCb.setChecked(true);
		}
		// 初始化参数值
		mDxEt7.setText(String.valueOf(mConfigManager.getDx()));
		mDyEt7.setText(String.valueOf(mConfigManager.getDy()));
		mDzEt7.setText(String.valueOf(mConfigManager.getDz()));
		mWxEt.setText(String.valueOf(mConfigManager.getWx()));
		mWyEt.setText(String.valueOf(mConfigManager.getWy()));
		mWyEt.setText(String.valueOf(mConfigManager.getWz()));
		mDmEt.setText(String.valueOf(mConfigManager.getDm()));
		mDxEt.setText(String.valueOf(mConfigManager.getDx()));
		mDyEt.setText(String.valueOf(mConfigManager.getDy()));
		mDzEt.setText(String.valueOf(mConfigManager.getDz()));
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.location_trans_titile2:
			ExpandAnimation animation2 = new ExpandAnimation(mLocationTwoView, 200);
			mLocationTwoView.startAnimation(animation2);
			break;
		case R.id.location_trans_titile3:
			ExpandAnimation animation3 = new ExpandAnimation(mLocationThreeView, 200);
			mLocationThreeView.startAnimation(animation3);
			break;
		case R.id.three_params_cb:
			if (mThreeParamsCb.isChecked())
			{
				mSevenParamsCb.setChecked(false);
				mConfigManager.setTransStr("三参数");
			}
			else
			{
				mConfigManager.setTransStr("");
			}
			saveParams();
			break;
		case R.id.seven_params_cb:
			if (mSevenParamsCb.isChecked())
			{
				mConfigManager.setTransStr("七参数");
				mThreeParamsCb.setChecked(false);
			}
			else
			{
				mConfigManager.setTransStr("");
			}
			saveParams();
			break;
		case R.id.threeparams_history_tv:
			showThreeParamsHisView();
			break;
		case R.id.sevenparams_history_tv:
			showSevenParamsHisView();
			break;
		case R.id.title_back:
			// String threeParamsStr = "△Dx = " +mElpTransParam.dx +",△Dy = "+
			// mElpTransParam.dy+ ",△Dz= " +mElpTransParam.dz+"";
			saveParams();
			String threeParamsStr = mElpTransParam.dx + ",    " + mElpTransParam.dy + ",     " + mElpTransParam.dz;
			saveText(threeParamsStr);
			String sevenParamStr = mElpTransParam.dx + ",  " + mElpTransParam.dy + ",   " + mElpTransParam.dz + ",   " + mElpTransParam.wx + ",   "
					+ mElpTransParam.wy + ",   " + mElpTransParam.wz + ",   " + mElpTransParam.dm;
			saveSevenParams(sevenParamStr);
			finish();
			break;
		default:
			break;
		}

	}

	/**
	 * 保存三参数、七参数
	 */
	private void saveParams()
	{
		if (mThreeParamsCb.isChecked())
		{
			mElpTransParam.type = 0;
			mElpTransParam.dx = Double.valueOf(mDxEt.getText().toString());
			mElpTransParam.dy = Double.valueOf(mDyEt.getText().toString());
			mElpTransParam.dz = Double.valueOf(mDzEt.getText().toString());

			mConfigManager.setDx(mElpTransParam.dx);
			mConfigManager.setDy(mElpTransParam.dy);
			mConfigManager.setDz(mElpTransParam.dz);
			mConfigManager.saveConfig();
		}

		if (mSevenParamsCb.isChecked())
		{
			mElpTransParam.type = 1;
			mElpTransParam.dx = Double.valueOf(mDxEt7.getText().toString());
			mElpTransParam.dy = Double.valueOf(mDyEt7.getText().toString());
			mElpTransParam.dz = Double.valueOf(mDzEt7.getText().toString());
			mElpTransParam.wx = Double.valueOf(mWxEt.getText().toString());
			mElpTransParam.wy = Double.valueOf(mWyEt.getText().toString());
			mElpTransParam.wz = Double.valueOf(mWzEt.getText().toString());
			mElpTransParam.dm = Double.valueOf(mDmEt.getText().toString());

			mConfigManager.setDx(mElpTransParam.dx);
			mConfigManager.setDy(mElpTransParam.dy);
			mConfigManager.setDz(mElpTransParam.dz);
			mConfigManager.setWx(mElpTransParam.wx);
			mConfigManager.setWy(mElpTransParam.wy);
			mConfigManager.setWz(mElpTransParam.wz);
			mConfigManager.setDm(mElpTransParam.dm);
			mConfigManager.saveConfig();
		}

	}

	/**
	 * 动画监听
	 * 
	 * @author fjl
	 * 
	 */
	class MyAnimationListener implements AnimationListener
	{
		@Override
		public void onAnimationEnd(Animation arg0)
		{

		}

		@Override
		public void onAnimationRepeat(Animation arg0)
		{

		}

		@Override
		public void onAnimationStart(Animation arg0)
		{

		}

	}

	class RadioButtonListen implements com.zondy.mapgis.android.view.CustomNestRadioGroup.OnCheckedChangeListener
	{

		@Override
		public void onCheckedChanged(CustomNestRadioGroup group, int checkedId)
		{

			if (group.getId() == R.id.coord_type_rg)
			{
				if (checkedId == R.id.gps_coord_rb)
				{
					mConfigManager.setCoordType("GPS");
				}
				if (checkedId == R.id.gcj_coord_rb)
				{
					mConfigManager.setCoordType("GCJ02");
				}
			}

			mConfigManager.saveConfig();
		}

	}

	/**
	 * 显示三参数历史记录
	 */
	private void showThreeParamsHisView()
	{
		View threeParamHisView = getLayoutInflater().inflate(R.layout.view_history_threeparams, null);
		mThreeParamHisListView = (ListView) threeParamHisView.findViewById(R.id.threeparams_lv);
		inflateListView();
		AlertDialog.Builder alertDialog = DialogUtil.createNobuttonDialog(this, null, null, threeParamHisView, null);
		final Dialog dialog = alertDialog.show();
		mThreeParamHisListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				String params = mThreeParamHisArrays[position];
				String[] strs = params.split(",");
				if (strs.length > 1)
				{
					mDxEt.setText(strs[0]);
					mDyEt.setText(strs[1]);
					mDzEt.setText(strs[2]);
				}
				dialog.dismiss();

			}
		});
	}

	/**
	 * 显示三参数历史记录
	 */
	private void showSevenParamsHisView()
	{
		View sevenParamHisView = getLayoutInflater().inflate(R.layout.view_history_sevenparams, null);
		ListView sevenParamHisListView = (ListView) sevenParamHisView.findViewById(R.id.sevenparams_lv);
		inflateSevenParamsListView(sevenParamHisListView);
		AlertDialog.Builder alertDialog = DialogUtil.createNobuttonDialog(this, null, null, sevenParamHisView, null);
		final Dialog dialog = alertDialog.show();
		sevenParamHisListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				String params = mSevenParamHisArrays[position];
				String[] strs = params.split(",");
				if (strs.length > 5)
				{
					mDxEt7.setText(strs[0]);
					mDyEt7.setText(strs[1]);
					mDzEt7.setText(strs[2]);
					mWxEt.setText(strs[3]);
					mWyEt.setText(strs[4]);
					mWyEt.setText(strs[5]);
					mDmEt.setText(strs[6]);
				}
				dialog.dismiss();

			}
		});
	}

	/**
	 * 填充LisView
	 */
	private void inflateListView()
	{
		getHistory();
		// 新建适配器，适配器数据为搜索历史文件内容
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		for (String str : mThreeParamHisArrays)
		{
			Map listItem = new HashMap<String, Object>();
			listItem.put("params", str);
			listItems.add(listItem);
		}
		mThreeParamadapter = new SimpleAdapter(getApplicationContext(), listItems, R.layout.view_params_item, new String[] { "params" },
				new int[] { R.id.params_tv });
		mThreeParamHisListView.setAdapter(mThreeParamadapter);
	}

	/**
	 * 填充七参数历史LisView
	 */
	private void inflateSevenParamsListView(ListView listView)
	{
		getSevenParamsHistory();
		// 新建适配器，适配器数据为搜索历史文件内容
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		for (String str : mSevenParamHisArrays)
		{
			Map listItem = new HashMap<String, Object>();
			listItem.put("params", str);
			listItems.add(listItem);
		}
		SimpleAdapter sevenParamadapter = new SimpleAdapter(getApplicationContext(), listItems, R.layout.view_params_item, new String[] { "params" },
				new int[] { R.id.params_tv });
		listView.setAdapter(sevenParamadapter);
	}

	/**
	 * 保存用户输入文字（不重复添加）
	 * 
	 * @param text
	 */
	public void saveText(String text)
	{
		// 获取搜索框信息
		SharedPreferences mysp = getApplicationContext().getSharedPreferences("threeparams_history", Activity.MODE_MULTI_PROCESS);
		String old_text = mysp.getString("history", "");

		// 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
		StringBuilder builder = new StringBuilder(old_text);
		builder.append(text + ";");

		// 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
		if (!old_text.contains(text + ";"))
		{
			SharedPreferences.Editor myeditor = mysp.edit();
			myeditor.putString("history", builder.toString());
			myeditor.commit();
			// ToolToast.showShort("添加成功");
		}
		else
		{
			// ToolToast.showShort("已存在");
		}

	}

	public void getHistory()
	{
		// 获取搜索记录文件内容
		SharedPreferences sp = getApplicationContext().getSharedPreferences("threeparams_history", Activity.MODE_MULTI_PROCESS);
		String history = sp.getString("history", "暂时没有历史记录");
		// 用逗号分割内容返回数组
		mThreeParamHisArrays = history.split(";");

		// 保留前10条数据
		if (mThreeParamHisArrays.length > 10)
		{
			String[] newArrays = new String[10];
			// 实现数组之间的复制
			System.arraycopy(mThreeParamHisArrays, 0, newArrays, 0, 10);
			// mThreeParamadapter = new
			// ArrayAdapter<String>(getApplicationContext(),
			// android.R.layout.simple_dropdown_item_1line,
			// mThreeParamHisArrays);
		}
	}

	/**
	 * 清空用户输入记录
	 * 
	 * @param
	 */
	public void cleanHistory()
	{
		SharedPreferences sp = getApplicationContext().getSharedPreferences("threeparams_history", Activity.MODE_MULTI_PROCESS);
		SharedPreferences.Editor editor = sp.edit();
		editor.clear();
		editor.commit();
		// ToolToast.showShort("清除成功");
		super.onDestroy();
	}

	/**
	 * 保存用户输入文字（不重复添加）
	 * 
	 * @param text
	 */
	public void saveSevenParams(String text)
	{
		// 获取搜索框信息
		SharedPreferences mysp = getApplicationContext().getSharedPreferences("sevenparams_history", Activity.MODE_MULTI_PROCESS);
		String old_text = mysp.getString("history", "");

		// 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
		StringBuilder builder = new StringBuilder(old_text);
		builder.append(text + ";");

		// 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
		if (!old_text.contains(text + ";"))
		{
			SharedPreferences.Editor myeditor = mysp.edit();
			myeditor.putString("history", builder.toString());
			myeditor.commit();
		}
		else
		{
			// ToolToast.showShort("已存在");
		}

	}

	public void getSevenParamsHistory()
	{
		// 获取搜索记录文件内容
		SharedPreferences sp = getApplicationContext().getSharedPreferences("sevenparams_history", Activity.MODE_MULTI_PROCESS);
		String history = sp.getString("history", "暂时没有历史记录");
		// 用逗号分割内容返回数组
		mSevenParamHisArrays = history.split(";");

		// 保留前10条数据
		if (mSevenParamHisArrays.length > 10)
		{
			String[] newArrays = new String[10];
			// 实现数组之间的复制
			System.arraycopy(mSevenParamHisArrays, 0, newArrays, 0, 10);
		}
	}

	/**
	 * 清空用户输入记录
	 * 
	 * @param
	 */
	public void cleanSevenParamsHistory()
	{
		SharedPreferences sp = getApplicationContext().getSharedPreferences("sevenparams_history", Activity.MODE_MULTI_PROCESS);
		SharedPreferences.Editor editor = sp.edit();
		editor.clear();
		editor.commit();
		super.onDestroy();
	}

	@Override
	public void onBackPressed()
	{
		saveParams();
		String threeParamsStr = mElpTransParam.dx + ",    " + mElpTransParam.dy + ",     " + mElpTransParam.dz;
		saveText(threeParamsStr);
		String sevenParamStr = mElpTransParam.dx + ",  " + mElpTransParam.dy + ",   " + mElpTransParam.dz + ",   " + mElpTransParam.wx + ",   "
				+ mElpTransParam.wy + ",   " + mElpTransParam.wz + ",   " + mElpTransParam.dm;
		saveSevenParams(sevenParamStr);
		super.onBackPressed();
	}

}
